package com.cs342.uwosh.cloudycontacts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import com.cs342.uwosh.cloudycontacts.SimpleGestureFilter.SimpleGestureListener;
import com.cs342.uwosh.cloudycontacts.tasks.db.DeleteContactTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.GetAllCategoryNamesTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.GetAllContactTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.GetContactsByCategoryTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.GetUserDetailsTask;
import com.cs342.uwosh.cloudycontacts.tasks.network.AuthenticateCredentialsTask;
import com.cs342.uwosh.cloudycontacts.tasks.network.PostToCloudTask;
import com.google.gson.JsonObject;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
//////////////////////////////////////////
/////////// PROJECT CAMO START ///////////
//////////////////////////////////////////
public class MainActivity extends Activity implements SimpleGestureListener {
//////////////////////////////////////////
//////////// PROJECT CAMO EMD ////////////
//////////////////////////////////////////
	// UI Elements
	public EditText contactSearch;
	
	public static ListView listOfContacts;
	
	public static TextView allContactsView;
	public static TextView catOneView;
	public static TextView catTwoView;
	public static TextView catThreeView;
	public static TextView catFourView;
	public static TextView catFiveView;
	
	public static ArrayAdapter<Contact> contactListAdapter;
	
	public static Context mainContext;
	
	// Data Storage
	public static HashMap<String,Contact> allContacts = new HashMap<String,Contact>();
	public Contact longClickedContact;
	public static ArrayList<String> deletedContacts = new ArrayList<String>();
	
	
	// Primitive types
	public int categoryToEdit;
	public static int categoryViewed = 0;
	
	public static int CURRENT_USER;

	// Intent Related
	public static String EXTRA_MESSAGE;
	
	// Database Related
	public static SqlConnect db;
	
	/*
	 * Breakdown of indexing of the themes arrays
	 * [0] = App background color
	 * [1] = TextView category buttons at the top of MainActivity
	 * [2] = List items for main list of contacts
	 * [3] = CheckBoxPreferences on the Create/Edit categories activity
	 * [4] = All of the apps actual buttons
	 * [5] = Category "buttons" text
	 * [6] = All actual buttons text
	 * [7] = ListView text
	 * [8] = EditText text
	 */
	// Themes Arrays
	public static final int[] DEFAULT_THEME_ARRAY = 
			new int[] 
					{
					R.color.background_color_theme_default,
					R.color.category_btn_color_theme_default,
					R.color.list_item_color_theme_default,
					R.layout.custom_checkbox_theme_default,
					R.color.button_color_theme_default,
					R.style.ButtonText_theme_default,
					R.style.ButtonText_theme_default,
					R.style.ListItemText_theme_default,
					R.style.EditText_theme_default,
					R.color.category_btn_color_theme_default_pressed
					};
	
	public static final int[] ONE_THEME_ARRAY =
			new int[] 
					{
					R.color.background_color_theme_one,
					R.color.category_btn_color_theme_one,
					R.color.list_item_color_theme_one,
					R.layout.custom_checkbox_theme1_default,
					R.color.button_color_theme_one,
					R.style.ButtonText_theme1_default,
					R.style.ButtonText_theme1_default,
					R.style.ListItemText_theme1_default,
					R.style.EditText_theme1_default,
					R.color.category_btn_color_theme_one_pressed
					};
	
	public static final int[] TWO_THEME_ARRAY =
			new int[] 
					{
					R.color.background_color_theme_two,
					R.color.category_btn_color_theme_two,
					R.color.list_item_color_theme_two,
					R.layout.custom_checkbox_theme2_default,
					R.color.button_color_theme_two,
					R.style.ButtonText_theme2_default,
					R.style.ButtonText_theme2_default,
					R.style.ListItemText_theme2_default,
					R.style.EditText_theme2_default,
					R.color.category_btn_color_theme_two_pressed
					};
	
	public static final int[] THREE_THEME_ARRAY =
			new int[] 
					{
					R.color.background_color_theme_three,
					R.color.category_btn_color_theme_three,
					R.color.list_item_color_theme_three,
					R.layout.custom_checkbox_theme3_default,
					R.color.button_color_theme_three,
					R.style.ButtonText_theme3_default,
					R.style.ButtonText_theme3_default,
					R.style.ListItemText_theme3_default,
					R.style.EditText_theme3_default,
					R.color.category_btn_color_theme_three_pressed
					};
	
	
	
	// Theme Strings
	public static String THEME_DEFAULT = "Default";
	
	public static String THEME_ONE = "Chrome";
	
	public static String THEME_TWO = "Forest";
	
	public static String THEME_THREE = "Hello Kitty";


	public static String CURRENT_THEME = THEME_DEFAULT;


	//////////////////////////////////////////
	/////////// PROJECT CAMO START ///////////
	//////////////////////////////////////////
	
	private SimpleGestureFilter detector; 
	
	//////////////////////////////////////////
	//////////// PROJECT CAMO EMD ////////////
	//////////////////////////////////////////




	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		String[] userDetails = new String[2];
		try
		{
			userDetails = new GetUserDetailsTask().execute().get();
			
		}
		catch(Exception e)
		{
			
			userDetails = new String [] {"",""};
		}
		System.out.println(userDetails[0]+"aaaaaaaaaaaaaaaaaaaaaaa");
		boolean logged = false;
		try {
			logged = new AuthenticateCredentialsTask().execute(userDetails[0],userDetails[1]).get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		
		setContentView(R.layout.activity_main);
		
		mainContext = this;

		db = new SqlConnect(this);
		
		allContactsView = (TextView) findViewById(R.id.allCons);
		catOneView = (TextView) findViewById(R.id.catOne);
		catTwoView = (TextView) findViewById(R.id.catTwo);
		catThreeView = (TextView) findViewById(R.id.catThree);
		catFourView = (TextView) findViewById(R.id.catFour);
		catFiveView = (TextView) findViewById(R.id.catFive);

		listOfContacts = (ListView) findViewById(R.id.contactsListView);
		contactSearch = (EditText) findViewById(R.id.contactSearch);
		System.out.println(logged);
		System.out.println(userDetails[0]);
		System.out.println(userDetails[1]);
		if(!logged)
		{
			Intent intent = new Intent(this,LoginActivity.class);
			startActivity(intent);
		}
		else
		{
			new GetAllContactTask().execute();
		}
		//new GetAllContactTask().execute();

		listOfContacts.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long arg3)
			{
				Contact clickedContact = contactListAdapter.getItem(position);
				viewContact(clickedContact);
			}
		});
		registerForContextMenu(listOfContacts);
		registerForContextMenu(catOneView);
		registerForContextMenu(catTwoView);
		registerForContextMenu(catThreeView);
		registerForContextMenu(catFourView);
		registerForContextMenu(catFiveView);

		allContactsView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				clickAllCons();
			}
		});

		catOneView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				clickOne();
			}
		});

		catTwoView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				clickTwo();
			}
		});

		catThreeView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				clickThree();
			}
		});

		catFourView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				clickFour();
			}
		});

		catFiveView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				clickFive();
			}
		});

		new GetAllCategoryNamesTask().execute();
		
		contactSearch.addTextChangedListener(new TextWatcher(){

			@Override
			public void afterTextChanged(Editable arg0)
			{
				
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
			{
				
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
			{
				contactListAdapter.getFilter().filter(arg0);
			}
		});
		
		findViewById(R.id.syncDat).setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				String[] details = new String[2];
				try {
					details = new GetUserDetailsTask().execute().get();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
				boolean loggedIn = false;
				try {
					loggedIn = new AuthenticateCredentialsTask().execute(details[0],details[1]).get();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
				if (loggedIn)
				{
					new PostToCloudTask().execute(details[0],details[1]);
				}
			}
		});
		
		
		
		changeCategoyButtonBackground(allContactsView);
		
		
		
		//////////////////////////////////////////
		/////////// PROJECT CAMO START ///////////
		//////////////////////////////////////////
		detector = new SimpleGestureFilter(this,this);
		//////////////////////////////////////////
		//////////// PROJECT CAMO EMD ////////////
		//////////////////////////////////////////
	}
	
	/**
	 * Things to happen on resume:
	 * display the correct names for all categories
	 * display the correct list for which category should be shown
	 * should probably highlight the category being viewed in a diff color
	 */
	@Override
	public void onResume()
	{
		super.onResume();
		if (MainActivity.CURRENT_THEME.equals(MainActivity.THEME_DEFAULT))
        {
			applyTheme(MainActivity.DEFAULT_THEME_ARRAY);
        }
        else if (MainActivity.CURRENT_THEME.equals(MainActivity.THEME_ONE))
        {
        	applyTheme(MainActivity.ONE_THEME_ARRAY);
        }
        else if (MainActivity.CURRENT_THEME.equals(MainActivity.THEME_TWO))
        {
        	applyTheme(MainActivity.TWO_THEME_ARRAY);
        }
        else if (MainActivity.CURRENT_THEME.equals(MainActivity.THEME_THREE))
        {
        	applyTheme(MainActivity.THREE_THEME_ARRAY);
        }
		
		if (categoryViewed != 0)
		{
			switch(categoryViewed)
			{
			case 1:
				changeCategoyButtonBackground(catOneView);
				clickOne();
				break;
			case 2:
				changeCategoyButtonBackground(catTwoView);
				clickTwo();
				break;
				
			case 3:
				changeCategoyButtonBackground(catThreeView);
				clickThree();
				break;
				
			case 4:
				changeCategoyButtonBackground(catFourView);
				clickFour();
				break;
				
			case 5:
				changeCategoyButtonBackground(catFiveView);
				clickFive();
				break;
			}
			
			new GetContactsByCategoryTask().execute(categoryViewed);
		}
		else
		{
			changeCategoyButtonBackground(allContactsView);
			clickAllCons();
		}
		
		
	}
	

	
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		if (v == listOfContacts)
		{
			inflater.inflate(R.menu.contacts_list_context_menu, menu);
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			longClickedContact = contactListAdapter.getItem(info.position);
		}
		else if (v == catOneView)
		{
			this.categoryToEdit = 1;
			inflater.inflate(R.menu.long_click_category_context_menu, menu);
		}
		else if (v == catTwoView)
		{
			this.categoryToEdit = 2;
			inflater.inflate(R.menu.long_click_category_context_menu, menu);			
		}
		else if (v == catThreeView)
		{
			this.categoryToEdit = 3;
			inflater.inflate(R.menu.long_click_category_context_menu, menu);		
		}
		else if (v == catFourView)
		{
			this.categoryToEdit = 4;
			inflater.inflate(R.menu.long_click_category_context_menu, menu);		
		}
		else if (v == catFiveView)
		{
			this.categoryToEdit = 5;
			inflater.inflate(R.menu.long_click_category_context_menu, menu);
		}
		else
		{
		}
		
	}

	
	
	
	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		@SuppressWarnings("unused")
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.delete_contact:
			deleteContact(longClickedContact);
			return true;
		case R.id.edit_category:
			Intent intent = new Intent(this, CreateEditCategoryActivity.class);
			intent.putExtra(EXTRA_MESSAGE, ""+this.categoryToEdit);
			startActivity(intent);
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}
	
	
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case R.id.delete_contact:
			Intent intent1 = new Intent(this, DeleteContactsChooser.class);
			startActivity(intent1);
			return true;
		case R.id.create_category:
			final int totalCategories = db.categoryCount();
			if(totalCategories < 5)
			{
				switch(totalCategories + 1)
				{
					case 1:
						clickOne();
						return true;
					case 2:
						clickTwo();
						return true;
					case 3:
						clickThree();
						return true;
					case 4:
						clickFour();
						return true;
					case 5:
						clickFive();
						return true;
					}
					return true;
			}
			else
			{
				showCategorySelector();
			}
			return true;
		case R.id.edit_category_menu:
			showCategorySelector();
			return true;
		case R.id.add_contact:
			Intent intent2 = new Intent(this, AddContact.class);
			startActivity(intent2);
			return true;
		case R.id.themes:
			generateThemesDialog();
			return true;
		case R.id.login_opt:
			String[] x = new String[2];
			
			if (db.getUserId() != 0)
			{
				x = db.getUser();
				new PostToCloudTask().execute(x[0],x[1]);
			}
			
			Intent intent = new Intent(this,LoginActivity.class);
			startActivity(intent);
			return true;
		case R.id.logout_opt:
			MainActivity.db.createUser(new String[] {"",""},0);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
		
	}
	
	/**
	 * Applies the theme to all UI elements in this activity
	 * @param themeToApply The int array that points to all the xml files used to generate the theme
	 * [0] = App background color
	 * [1] = TextView category buttons at the top of MainActivity
	 * [2] = List items for main list of contacts
	 * [3] = CheckBoxPreferences on the Create/Edit categories activity
	 * [4] = All of the apps actual buttons
	 * [5] = Category "buttons" text
	 * [6] = All actual buttons text
	 * [7] = ListView text
	 * [8] = EditText text
	 */
	private void applyTheme(int[] themeToApply)
	{
		findViewById(R.id.main_activity_mainLayout).setBackgroundResource(themeToApply[0]);
		applyCategoryButtonThemes(new TextView[] 
				{
				(TextView) findViewById(R.id.catOne),
				(TextView) findViewById(R.id.catTwo),
				(TextView) findViewById(R.id.catThree),
				(TextView) findViewById(R.id.catFour),
				(TextView) findViewById(R.id.catFive),
				(TextView) findViewById(R.id.allCons)
				},
				themeToApply[1],themeToApply[5]);
		findViewById(R.id.addContact).setBackgroundResource(themeToApply[4]);
		findViewById(R.id.syncDat).setBackgroundResource(themeToApply[4]);
		TextView search = (TextView) findViewById(R.id.contactSearch);
		search.setTextAppearance(this, themeToApply[8]);
		switch(categoryViewed)
		{
		case 0:
			findViewById(R.id.allCons).setBackgroundResource(themeToApply[9]);
			break;
		case 1:
			findViewById(R.id.catOne).setBackgroundResource(themeToApply[9]);
			break;
		case 2:
			findViewById(R.id.catTwo).setBackgroundResource(themeToApply[9]);
			break;
		case 3:
			findViewById(R.id.catThree).setBackgroundResource(themeToApply[9]);
			break;
		case 4:
			findViewById(R.id.catFour).setBackgroundResource(themeToApply[9]);
			break;
		case 5:
			findViewById(R.id.catFive).setBackgroundResource(themeToApply[9]);
			break;
		}
	}
	
	/**
	 * Applies proper background and text style to an array of textviews
	 */
	private void applyCategoryButtonThemes(TextView[] categoryButtons, int backgroundID, int styleID)
	{
		for(TextView tv: categoryButtons)
		{
			tv.setBackgroundResource(backgroundID);
			tv.setTextAppearance(mainContext, R.style.ButtonText_theme_default);
		}
	}
	
	
	/**
	 * This function is called to display the themes dialog
	 * The user selects which theme they want to apply.
	 */
	private void generateThemesDialog()
	{
		final CharSequence[] themesList = new CharSequence[] 
				{
				THEME_DEFAULT,
				THEME_ONE,
				THEME_TWO,
				THEME_THREE
				};
		AlertDialog.Builder themesDialog = new AlertDialog.Builder(this);
		
		themesDialog.setTitle("Choose Your Theme");
		
		themesDialog.setSingleChoiceItems(themesList, -1, new DialogInterface.OnClickListener()
		{
			
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				if (themesList[which].equals(THEME_DEFAULT))
				{
					MainActivity.CURRENT_THEME = MainActivity.THEME_DEFAULT;
					applyTheme(DEFAULT_THEME_ARRAY);
					new GetAllContactTask().execute();
					dialog.cancel();
				}
				else if (themesList[which].equals(THEME_ONE))
				{
					MainActivity.CURRENT_THEME = MainActivity.THEME_ONE;
					applyTheme(ONE_THEME_ARRAY);
					new GetAllContactTask().execute();
					dialog.cancel();
				}
				else if (themesList[which].equals(THEME_TWO))
				{
					MainActivity.CURRENT_THEME = MainActivity.THEME_TWO;
					applyTheme(TWO_THEME_ARRAY);
					new GetAllContactTask().execute();
					dialog.cancel();
				}
				else if (themesList[which].equals(THEME_THREE))
				{
					MainActivity.CURRENT_THEME = MainActivity.THEME_THREE;
					applyTheme(THREE_THEME_ARRAY);
					new GetAllContactTask().execute();
					dialog.cancel();
				}
			}
		});
		themesDialog.show();
	}
	
	//////////////////////////////////////////////////////////
	///// USE TO MAKE THEME DIALOG ///////////////////////////
	//////////////////////////////////////////////////////////
	private void showCategorySelector() 
	{
		final CharSequence[] categoriesList = {catOneView.getText(),catTwoView.getText(), 
				catThreeView.getText(), catFourView.getText(), catFiveView.getText()};
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Select Category");

		alert.setSingleChoiceItems(categoriesList,-1, new 

		DialogInterface.OnClickListener()
		{

		    @Override
		    public void onClick(DialogInterface dialog, int which) 
		    {
		    	if(categoriesList[which] == catOneView.getText())
		    	{
		    		editCategoryMenu(1);
		    		dialog.cancel();
		    	}
		    	else if(categoriesList[which] == catTwoView.getText())
		    	{
		    		editCategoryMenu(2);
		    		dialog.cancel();
		    	}
		    	else if(categoriesList[which] == catThreeView.getText())
		    	{
		    		editCategoryMenu(3);
		    		dialog.cancel();
		    	}
		    	else if(categoriesList[which] == catFourView.getText())
		    	{
		    		editCategoryMenu(4);
		    		dialog.cancel();
		    	}
		    	else if(categoriesList[which] == catFiveView.getText())
		    	{
		    		editCategoryMenu(5);
		    		dialog.cancel();
		    	}
		    }

		});
		alert.show();
	}
	
	private void editCategoryMenu(int catID)
	{
		Intent intent = new Intent(this, CreateEditCategoryActivity.class);
		intent.putExtra(EXTRA_MESSAGE, ""+catID);
		startActivity(intent);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_menu, menu);
		return true;
	}

	/**
	 * Passes in a contact and then passes their ID to the DisplayContact
	 * activity.
	 * @param contact The contact who's ID is being passed to DisplayContact
	 */
	public void viewContact(Contact contact)
	{
		Intent intent = new Intent(this, AddContact.class);
		intent.putExtra(EXTRA_MESSAGE, ""+contact.getId());
		startActivity(intent);
	}
	/**
	 * Opens the add contact activity
	 * @param view
	 */
	public void add(View view){
		Intent intent = new Intent(this, AddContact.class);
		startActivity(intent);
		
	}
	/**
	 * Called to delete a contact
	 * @param contactToDelete The contact to be deleted.
	 */
	public void deleteContact(Contact contactToDelete)
	{
		new DeleteContactTask().execute(contactToDelete);
	}

	
	public void changeCategoyButtonBackground(TextView clickedView)
	{
		int[] themeToUse = null;
		
		if (CURRENT_THEME.equals(THEME_DEFAULT))
		{
			themeToUse = DEFAULT_THEME_ARRAY;
		}
		else if (CURRENT_THEME.equals(THEME_ONE))
		{
			themeToUse = ONE_THEME_ARRAY;
		}
		else if (CURRENT_THEME.equals(THEME_TWO))
		{
			themeToUse = TWO_THEME_ARRAY;
		}
		else if (CURRENT_THEME.equals(THEME_THREE))
		{
			themeToUse = THREE_THEME_ARRAY;
		}
		
		applyCategoryButtonThemes(new TextView[] 
				{(TextView) findViewById(R.id.catOne),
				(TextView) findViewById(R.id.catTwo),
				(TextView) findViewById(R.id.catThree),
				(TextView) findViewById(R.id.catFour),
				(TextView) findViewById(R.id.catFive),
				(TextView) findViewById(R.id.allCons)},
				themeToUse[1],themeToUse[5]);
		
		
		if (CURRENT_THEME.equals(THEME_DEFAULT))
		{
			clickedView.setBackgroundResource(R.color.category_btn_color_theme_default_pressed);
		}
		else if (CURRENT_THEME.equals(THEME_ONE))
		{
			clickedView.setBackgroundResource(R.color.category_btn_color_theme_one_pressed);
		}
		else if (CURRENT_THEME.equals(THEME_TWO))
		{
			clickedView.setBackgroundResource(R.color.category_btn_color_theme_two_pressed);
		}
		else if (CURRENT_THEME.equals(THEME_THREE))
		{
			clickedView.setBackgroundResource(R.color.category_btn_color_theme_three_pressed);
		}
	}
	
	
	public void clickAllCons()
	{
		new GetAllContactTask().execute();
		categoryViewed = 0;
		changeCategoyButtonBackground(allContactsView);
	}

	public void clickOne()
	{
        final int totalCategories = db.categoryCount();
        if(totalCategories < 1)
        {
        	DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
        	{
        	    @Override
        	    public void onClick(DialogInterface dialog, int which)
        	    {
        	        switch (which)
        	        {
        	        case DialogInterface.BUTTON_POSITIVE:
        	        	launchCreateEditCategory(totalCategories);
        	            break;
        	        case DialogInterface.BUTTON_NEGATIVE:
        	            break;
        	        }
        	    }
        	};
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setMessage("Create Category?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
        }
        else
        {
        	new GetContactsByCategoryTask().execute(1);
        	changeCategoyButtonBackground(catOneView);
        	categoryViewed = 1;
        }
	}
	
	public void launchCreateEditCategory(int totalCategories)
	{
		totalCategories++;
		Intent intent = new Intent(this, CreateEditCategoryActivity.class);
		intent.putExtra(EXTRA_MESSAGE, ""+totalCategories);
		startActivity(intent);
	}
	
	public void clickTwo()
	{
		final int totalCategories = db.categoryCount();
        if(totalCategories < 2)
        {
        	DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
        	{
        	    @Override
        	    public void onClick(DialogInterface dialog, int which)
        	    {
        	        switch (which)
        	        {
        	        case DialogInterface.BUTTON_POSITIVE:
        	        	launchCreateEditCategory(totalCategories);
        	            break;
        	        case DialogInterface.BUTTON_NEGATIVE:
        	            break;
        	        }
        	    }
        	};
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setMessage("Create Category?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
        }
        else
        {
        	new GetContactsByCategoryTask().execute(2);
        	changeCategoyButtonBackground(catTwoView);
        	categoryViewed = 2;
        }
	}
	
	public void clickThree()
	{
		final int totalCategories = db.categoryCount();
        if(totalCategories < 3)
        {
        	DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
        	{
        	    @Override
        	    public void onClick(DialogInterface dialog, int which)
        	    {
        	        switch (which)
        	        {
        	        case DialogInterface.BUTTON_POSITIVE:
        	        	launchCreateEditCategory(totalCategories);
        	            break;
        	        case DialogInterface.BUTTON_NEGATIVE:
        	            break;
        	        }
        	    }
        	};
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setMessage("Create Category?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
        }
        else
        {
        	new GetContactsByCategoryTask().execute(3);
        	changeCategoyButtonBackground(catThreeView);
        	categoryViewed = 3;
        }
	}
	
	public void clickFour()
	{
		final int totalCategories = db.categoryCount();
        if(totalCategories < 4)
        {
        	DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
        	{
        	    @Override
        	    public void onClick(DialogInterface dialog, int which)
        	    {
        	        switch (which)
        	        {
        	        case DialogInterface.BUTTON_POSITIVE:
        	        	launchCreateEditCategory(totalCategories);
        	            break;
        	        case DialogInterface.BUTTON_NEGATIVE:
        	            break;
        	        }
        	    }
        	};
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setMessage("Create Category?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
        }
        else
        {
        	new GetContactsByCategoryTask().execute(4);
        	changeCategoyButtonBackground(catFourView);
        	categoryViewed = 4;
        }
	}
	
	public void clickFive()
	{
		final int totalCategories = db.categoryCount();
        if(totalCategories < 5)
        {
        	DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
        	{
        	    @Override
        	    public void onClick(DialogInterface dialog, int which)
        	    {
        	        switch (which)
        	        {
        	        case DialogInterface.BUTTON_POSITIVE:
        	        	launchCreateEditCategory(totalCategories);
        	            break;
        	        case DialogInterface.BUTTON_NEGATIVE:
        	            break;
        	        }
        	    }
        	};
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setMessage("Create Category?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
        }
        else
        {
        	new GetContactsByCategoryTask().execute(5);
        	changeCategoyButtonBackground(catFiveView);
        	categoryViewed = 5;
        }
	}

//////////////////////////////////////////
/////////// PROJECT CAMO START ///////////
//////////////////////////////////////////
	private void swipeToLeft()
	{
		if (MainActivity.categoryViewed == 0)
		{
			clickOne();
		}
		else if (MainActivity.categoryViewed == 1)
		{
			clickTwo();
		}
		else if (MainActivity.categoryViewed == 2)
		{
			clickThree();
		}
		else if (MainActivity.categoryViewed == 3)
		{
			clickFour();
		}
		else if (MainActivity.categoryViewed == 4)
		{
			clickFive();
		}
		else if (MainActivity.categoryViewed == 5)
		{
			clickAllCons();
		}
	}
	
	private void swipeToRight()
	{
		if (MainActivity.categoryViewed == 0)
		{
			clickFive();
		}
		else if (MainActivity.categoryViewed == 1)
		{
			clickAllCons();
		}
		else if (MainActivity.categoryViewed == 2)
		{
			clickOne();
		}
		else if (MainActivity.categoryViewed == 3)
		{
			clickTwo();
		}
		else if (MainActivity.categoryViewed == 4)
		{
			clickThree();
		}
		else if (MainActivity.categoryViewed == 5)
		{
			clickFour();
		}
	}
	
	@Override
    public boolean dispatchTouchEvent(MotionEvent me){
		this.detector.onTouchEvent(me);
		return super.dispatchTouchEvent(me);
	}
	
	
	@Override
	public void onSwipe(int direction) {
		  switch (direction) {
		  case SimpleGestureFilter.SWIPE_RIGHT :
			  swipeToRight();
			  break;
		  case SimpleGestureFilter.SWIPE_LEFT :
			  swipeToLeft();
			  break;
		  case SimpleGestureFilter.SWIPE_DOWN :
			  break;
		  case SimpleGestureFilter.SWIPE_UP :
			  break;
		  } 
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		if (db.getUserId() != 0)
		{
			try {
				String[] str = new GetUserDetailsTask().execute().get();
				new PostToCloudTask().execute(str[0],str[1]);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}

	}

	public void onStop()
	{
		super.onStop();
		System.out.println("OMFG IT FUCKING STOPPED");

	}
	
	public void onPause()
	{
		super.onPause();
		
	}
	
	@Override
	public void onDoubleTap() {
		//Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show(); 
		Intent intent = new Intent(this,DisplayFromJson.class);
		startActivity(intent);
	}
//////////////////////////////////////////
////////////PROJECT CAMO EMD ////////////
//////////////////////////////////////////
}
